<?php
require_once "site_config.php";
require_once "ra_global.php";
// 油码验证，优惠码验证
$method = $_GET['method'];
if($method == "checkcode"){
    $promoCode = $_GET['promocode'];
    $userId = $_GET['userid'];

    echo checkCodeResult($db, $promoCode, $userId);
}

// 优惠码验证
function checkCodeResult($db, $promoCode, $userId) {
    $result = array();

    // 判断有没有优惠码核销活动
    $now = time();
    $activity = $db->ig2_want('mae_promocode_activity','status=1 and starttime<='.$now.' and endtime>='.$now);
    if (!$activity) {
        $result['errcode'] = 1;
        $result['errmsg'] = '验证失败<br/>目前没有开启的优惠码核销活动';
        return json_encode($result);
    }
    // 只有店员才能扫优惠码
    $user=$db->ig2_want('mae_user','role_type=2 and id='.$userId);
    if (!$user) {
        $result['errcode'] = 1;
        $result['errmsg'] = '亲爱的店长，非常抱歉，只有店员可以参与优惠码验证';
        return json_encode($result);
    }

    $role=$db->ig2_want('mae_role','is_delete=0 and role_type=2 and uid='.$userId);
    if (!$role) {
        $result['errcode'] = 1;
        $result['errmsg'] = '亲爱的店长，非常抱歉，只有店员可以参与优惠码验证';
        return json_encode($result);
    }

    // 优惠码不存在
    $dbPromoCode = $db->ig2_want('mae_promocode', 'promocode=upper("'.$promoCode.'")');
    if (!$dbPromoCode) {
        $result['errcode'] = 1;
        $result['errmsg'] = "验证失败<br/>此优惠码错误，请核实后重新输入";
        return json_encode($result);
    }
    // 优惠码已经被使用
    if ($dbPromoCode['status'] == 1){
        $result['errcode'] = 1;
        $result['errmsg'] = '验证失败，此优惠码已被使用，无法重复优惠';
        return json_encode($result);
    }

    $db->ig2_query('BEGIN');
    $success = $db->ig2_query("UPDATE mae_promocode SET status=1 WHERE promocode='".$promoCode."'");
    if ($success) {
        $success = $db->ig2_query("INSERT INTO mae_promocode_exchange_log (userid, activityid, activityname, score, createtime) VALUES (".$userId.", ".$activity['id'].", '".$activity['activityname']."', 5, ".$now.")");
    }

    if ($success) {
        $success = $db->ig2_query("update mae_user set score=score+5 WHERE id=".$userId);
    }

    if ($success) {
        $post_data = array(
            'promocode' => $promoCode,
            'consume_time' => time()
        );
        send_post('http://wxebdb5c1147797c17.mp.weixinhost.com/addon/private-shell-coupon?a=consume_coupon', $post_data);

        $db->ig2_query('COMMIT');
        $result['errcode'] = 0;
    } else {
        $db->ig2_query('ROLLBACK');
        $result['errcode'] = 1;
        $result['errmsg'] = '服务器异常';
    }

    return json_encode($result);
}

function send_post($url, $post_data) {

    $postdata = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 15 * 60 // 超时时间（单位:s）
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return $result;
}

//使用方法
$post_data = array(
    'username' => 'stclair2201',
    'password' => 'handan'
);
send_post('http://www.qianyunlai.com', $post_data);
?>